# MACD指标分析
from datacache import get_stock_data
import talib
import pandas as pd
import matplotlib.pyplot as plt

def main():
    stock_code = 'sh603056'  # 平安银行
    start_date = '20200101'
    end_date = '20250130'
    df = get_stock_data(stock_code, start_date, end_date)
    close_price = df['close']
    macd, signal, hist = talib.MACD(close_price, fastperiod=12, slowperiod=26, signalperiod=9)

    # 根据 macd 决定买入卖出时机
    wallet_funds = 10000  # 初始资金10000
    holding = 0  # 持有股票数量
    sell_warning = False  # 卖出警告 下一个交易日开盘卖出
    holding_price = 0  # 持有股票价格
    sum_profit = []  # 收益曲线

    for index, row in df.iterrows():
        row_date = row['date']
        close_price = row['close']
        open_price = row['open']
        high_price = row['high']  # 最高价
        low_price = row['low']  # 最低价
        volume = row['volume']
        turnover = row['turnover']  # 换手率

        if holding > 0:
            # 添加策略， 第二天以尾盘价格卖出
            prepared_amount = close_price * holding
            wallet_funds = wallet_funds + prepared_amount  # 加上卖出金额
            holding = 0  # 更新持有数量
            holding_price = close_price  # 更新持有价格

        if index > 5:
            if macd[index] > 0 and macd[index - 1] < 0:
                # macd上穿0轴买入， 暂时只在尾盘买入
                if holding == 0:
                    prepare_holding = wallet_funds / close_price
                    wallet_funds = 0
                    holding_price = close_price
                    holding = prepare_holding
            if macd[index] < 0 and macd[index - 1] > 0:
                # macd下穿0轴卖出，暂时只在尾盘卖出
                if holding > 0:
                    prepared_amount = close_price * holding
                    wallet_funds = wallet_funds + prepared_amount  # 加上卖出金额
                    holding = 0  # 更新持有数量
                    holding_price = close_price  # 更新持有价格
        sum_profit.append(wallet_funds + holding * close_price)


    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

    fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(14, 10), sharex=True)
    df['date'] = pd.to_datetime(df['date'])
    # 获取日期部分
    df['date'] = df['date'].dt.date
    # 绘制价格和移动平均线
    ax1.plot(df['date'], df['close'], label='收盘价', color='#0d0dff80')
    ax1.plot(df['date'], df['ma5'], label='5日均线', color='red')
    ax1.plot(df['date'], df['ma20'], label='20日均线', color='green')

    ax1.set_title('股票代码:' + stock_code)
    ax1.set_ylabel('价格')
    ax1.legend()

    ax2.set_title('macd:' + stock_code)
    ax2.plot(df['date'], macd, label='日期', color='red')
    ax2.set_ylabel('总量')
    ax2.legend()

    ax3.set_title('总资产:' + stock_code)
    ax3.plot(df['date'], sum_profit, label='日期', color='red')
    ax3.set_ylabel('总量')
    ax3.legend()

    plt.xlabel('日期')
    plt.tight_layout()
    plt.show()

if __name__ == "__main__":
    main()